﻿package yii.db.schema.sqlite{

	import yii.*;
	import phpas3.*;
	import yii.db.*;
	import yii.db.schema.*;

	import flash.data.*;
	import flash.net.*;

	public class CSqliteSchema extends CDbSchema{

	/**
	 * @var array the abstract column types mapped to physical column types+
	 * @since 1+1+6
	 */
	 public override function get columnTypes():Object{
	    return {
	        'pk' : 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
	        'string' : 'varchar(255)',
	        'text' : 'text',
	        'integer' : 'integer',
	        'float' : 'float',
	        'decimal' : 'decimal',
	        'datetime' : 'datetime',
	        'timestamp' : 'timestamp',
	        'time' : 'time',
	        'date' : 'date',
	        'binary' : 'blob',
	        'boolean' : 'tinyint(1)',
			'money' : 'decimal(19,4)'
	    }
	}














		public function CSqliteSchema( conn:CDbConnection ){
			super( conn );
		}





	/**
	 * Collects the foreign key column details for the given table+
	 * @param CDbTableSchema $table the table metadata
	 */
	protected function findConstraints( $table:CDbTableSchema ):void{
		//Yii.log( "foreignKeyは実装されていません" );
//		var $foreignKeys:Array = new Array();
//		var $sql:String = "PRAGMA foreign_key_list("+ $table.rawName +")";
//		var $keys = this.getDbConnection().createCommand($sql).queryAll();
//		for( var index in $keys ){
//			var $key = $keys[index];
//			var $column = $table.columns[$key['from']];
//			$column.isForeignKey = true;
//			$foreignKeys[$key['from']] = new Array( $key['table'], $key['to'] );
//		}
//		$table.foreignKeys = $foreignKeys;
	}




	/**
	 * Creates a table column+
	 * @param array $column column metadata
	 * @return CDbColumnSchema normalized column metadata
	 */
	protected function createColumn( $column:SQLColumnSchema ):CSqliteColumnSchema{
		var $c:CSqliteColumnSchema = new CSqliteColumnSchema();
		$c.name = $column.name;
		$c.rawName = this.quoteColumnName( $c.name );
		$c.allowNull = $column.allowNull;
		$c.isPrimaryKey = $column.primaryKey ;
		$c.isForeignKey = false;
		$c.init( strtolower($column.dataType), null );
		return $c;
	}







	/**
	 * Collects the table column metadata.
	 * @param CDbTableSchema $table the table metadata
	 * @return boolean whether the table exists in the database
	 */
	protected function findColumns( $table:CDbTableSchema ):Boolean{
		// AIR では PRAGMA が使えないので、ネイティブの loadSchema() を使う
		var result:SQLSchemaResult;
		var responder:Responder = new Responder(
			function(...args:Array):void{
				result = args[0];
			},
			function():void{
				Yii.log( $table.name +"が見つかりませんでした。" );
			}
		);
		this.connection.getPdoInstance().nativeConnection.loadSchema( SQLTableSchema, $table.name, "main", true, responder );
		if( !result ){
			return false;
		}

		var nativeTable:SQLTableSchema = result.tables[0];
		var $columns:Array = nativeTable.columns;
		for( var index in $columns ){
			var $column:SQLColumnSchema = $columns[index];
			var $c:CSqliteColumnSchema = this.createColumn( $column );
			$table.columns[$c.name] = $c;
			if( $c.isPrimaryKey ){
				if( $table.primaryKey===null ){
					$table.primaryKey = $c.name;
				} else if( is_string($table.primaryKey) ){
					$table.primaryKey = new Array( $table.primaryKey, $c.name );
				} else {
					$table.primaryKey.push( $c.name );
				}
			}
		}
		if( is_string($table.primaryKey) && !strncasecmp($table.columns[$table.primaryKey].dbType,'int',3) ){
			$table.sequenceName = '';
			$table.columns[$table.primaryKey].autoIncrement = true;
		}



//		var $sql:String = "PRAGMA table_info("+ $table.rawName +")";
//		var $columns:Array = this.getDbConnection().createCommand($sql).queryAll();
//		if( empty($columns) ){
//			return false;
//		}
//
//		for( var index in $columns ){
//			var $column = $columns[index];
//			var $c:CSqliteColumnSchema = this.createColumn($column);
//			$table.columns[$c.name] = $c;
//			if( $c.isPrimaryKey ){
//				if($table.primaryKey===null)
//					$table.primaryKey=$c.name;
//				else if( is_string($table.primaryKey) )
//					$table.primaryKey = new Array( $table.primaryKey, $c.name );
//				else
//					$table.primaryKey.push( $c.name );
//			}
//		}
//		if( is_string($table.primaryKey) && !strncasecmp($table.columns[$table.primaryKey].dbType,'int',3) ){
//			$table.sequenceName = '';
//			$table.columns[$table.primaryKey].autoIncrement = true;
//		}

		return true;
	}






	/**
	 * Loads the metadata for the specified table.
	 * @param string $name table name
	 * @return CDbTableSchema driver dependent table metadata. Null if the table does not exist.
	 */
	protected override function loadTable( $name:String ):CDbTableSchema{
		var $table:CDbTableSchema = new CDbTableSchema();
		$table.name = $name;
		$table.rawName = this.quoteTableName( $name );

		if( this.findColumns($table) ){
			this.findConstraints($table);
			return $table;
		} else {
			return null;
		}
	}



		protected override function createCommandBuilder():CDbCommandBuilder{
			return new CSqliteCommandBuilder( this );
		}



	}

}